package com.walnut.lom_system.service.impl;

import com.walnut.lom_system.common.annotation.DoLog;
import com.walnut.lom_system.common.lang.Const;
import com.walnut.lom_system.common.lang.LogConstants;
import com.walnut.lom_system.common.lang.OperateTypeContains;
import com.walnut.lom_system.domain.entity.MyUserDetails;
import com.walnut.lom_system.domain.entity.UserLoginInfo;
import com.walnut.lom_system.mapper.UserLoginInfoMapper;
import com.walnut.lom_system.service.UserLoginInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * MyUserDetailService通过数据库实现登录业务（身份校验）
 * @author walnut
 * @date 2021/11/6 5:15 下午
 * @version 1.0
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    private static final Logger LOG = LoggerFactory.getLogger(MyUserDetailServiceImpl.class);

    @Autowired
    private UserLoginInfoMapper loginInfoMapper;

    @Autowired
    private UserLoginInfoService loginInfoService;



    @Override
    @DoLog(operateModule = "LOGIN",operateType = OperateTypeContains.OPERATE_LOGIN, operateDesc = "登录", requestStyle = LogConstants.REQUEST_COMMON_STYLE)
    public UserDetails loadUserByUsername(String sid) throws UsernameNotFoundException {
        //通过数据库查询用户名是否存在
        //创建查询规则

        HashMap<String, Object> map = new HashMap<>();
        map.put("sid",sid);

        List<UserLoginInfo> userLoginInfos = loginInfoMapper.selectByMap(map);

        //数据库没有用户名，认证失败
        if (userLoginInfos.isEmpty()){
            LOG.info("用户不存在");
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (userLoginInfos.get(0).getState() != Const.USER_ON_USE){
            System.out.println("账号不可用");
            throw new BadCredentialsException("账户不可用");
        }

        //账号可用状态
        UserLoginInfo userLoginInfo = userLoginInfos.get(0);
        return new MyUserDetails(userLoginInfo.getId(), userLoginInfo.getSid(), userLoginInfo.getPassword()
        ,getUserAuthority(userLoginInfo.getId()));
    }

    /**
     * 获取用户权限信息(角色及菜单权限)
     * @param userId 用户id
     * @return 权限列表
     */
    public Collection<? extends GrantedAuthority> getUserAuthority(Long userId) {
        String authority = loginInfoService.getUserAuthorityInfo(userId);

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
